#pragma once
#include <iostream>
#include <string>
#include <strings.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <functional>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
namespace Client
{
    using namespace std;
    class udpClient
    {
    public:
        udpClient(const string &serverIp, const uint16_t serverPort)
            : _serverIp(serverIp), _serverPort(serverPort), _sockfd(-1) {}
        void initClient()
        {
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                cerr << "socket error:" << errno << strerror(errno) << endl;
                exit(2);
            }
        }
        void run()
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(_serverIp.c_str());
            server.sin_port = htons(_serverPort);
            while (1)
            {
                string message;
                cout << "请输入你想要翻译的单词：";
                getline(cin,message);
                //发送请求
                sendto(_sockfd, message.c_str(), message.size(), 0, (const struct sockaddr *)&server, sizeof(server));
                char buffer[1024];
                struct sockaddr_in temp;
                socklen_t len = sizeof(temp);
                //接受查询翻译结果
                size_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
                if (n >= 0)
                    buffer[n] = 0;
                cout << "翻译的结果为: " << buffer << endl;
            }
        }
 
    private:
        string _serverIp;
        int _sockfd;
        uint16_t _serverPort;
    };
}